package com.zangs.emqx_expand.system.component;

import com.zangs.emqx_expand.common.annotation.SignatureApi;
import com.zangs.emqx_expand.common.utils.sign.Md5Utils;
import com.zangs.emqx_expand.system.domain.Api;
import com.zangs.emqx_expand.system.service.IApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 将第接口信息保存到数据库
 */
@Component
public class ApiInfoInitializer implements CommandLineRunner {

    @Autowired
    private IApiService apiService;

    private final RequestMappingHandlerMapping requestMappingHandlerMapping;

    public ApiInfoInitializer(RequestMappingHandlerMapping requestMappingHandlerMapping) {
        this.requestMappingHandlerMapping = requestMappingHandlerMapping;
    }


    @Override
    public void run(String... args)  {
        apiService.deleteApiAll();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            HandlerMethod handlerMethod = entry.getValue();
            Class<?> beanType = handlerMethod.getBeanType();
            Method method = handlerMethod.getMethod();

            if (method.isAnnotationPresent(SignatureApi.class)) {
                RequestMappingInfo mappingInfo = entry.getKey();
                Set<String> urls = new HashSet<>();
                if (mappingInfo.getPatternsCondition() != null) {
                    urls = mappingInfo.getPatternsCondition().getPatterns();
                }
                Set<RequestMethod> methods = mappingInfo.getMethodsCondition().getMethods();
                SignatureApi signatureApi = method.getAnnotation(SignatureApi.class);
                String remark = signatureApi.remark(); // 获取注解的值
                Boolean signature = signatureApi.signature(); // 获取注解的值

                String methodName = beanType.getName() + "." + method.getName();
                apiService.insertApi(
                new Api(Md5Utils.hash(methodName), methodName,urls.toString(),methods.toString(),remark,signature));

            }
        }
    }
}




